package my.study.com.mysql.jdbc.examples.example1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Ex3 {

	/**
	 * Retrieving AUTO_INCREMENT column values in Updatable ResultSets
	 * 
	 * @param args
	 * @throws SQLException
	 * @throws ClassNotFoundException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 */
	public static void main(String[] args) throws SQLException,
			InstantiationException, IllegalAccessException,
			ClassNotFoundException {
		String url = "jdbc:mysql://localhost:3306/test";
		String user = "root";
		String password = "fanhongjie";

		Class.forName("com.mysql.jdbc.Driver").newInstance();
		Connection conn = DriverManager.getConnection(url, user, password);
		Statement stmt = null;
		ResultSet rs = null;
		try {
			//
			// Create a Statement instance that we can use for
			// 'normal' result sets as well as an 'updatable'
			// one, assuming you have a Connection 'conn' to
			// a MySQL database already available
			//
			stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,
					java.sql.ResultSet.CONCUR_UPDATABLE);
			//
			// Issue the DDL queries for the table for this example
			//
			stmt.executeUpdate("DROP TABLE IF EXISTS autoIncTutorial");
			stmt.executeUpdate("CREATE TABLE autoIncTutorial ("
					+ "priKey INT NOT NULL AUTO_INCREMENT, "
					+ "dataField VARCHAR(64), PRIMARY KEY (priKey))");
			//
			// Example of retrieving an AUTO INCREMENT key
			// from an updatable result set
			//
			rs = stmt.executeQuery("SELECT priKey, dataField "
					+ "FROM autoIncTutorial");
			rs.moveToInsertRow();
			rs.updateString("dataField", "AUTO INCREMENT here?");
			rs.insertRow();
			//
			// the driver adds rows at the end
			//
			rs.last();
			//
			// We should now be on the row we just inserted
			//
			int autoIncKeyFromRS = rs.getInt("priKey");
			rs.close();
			rs = null;
			System.out.println("Key returned for inserted row: "
					+ autoIncKeyFromRS);
		} finally {
			if (rs != null) {
				rs.close();

			}
			if (stmt != null) {
				stmt.close();
			}
			if (conn != null) {
				conn.close();
			}
		}
	}
}
